package controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;
import java.util.List;

import javax.swing.Timer;

public class Clock implements ActionListener {
	private Timer timer;
	private List<GameClockListener> gameClockListeners;
	private List<DrawingClockListener> drawingClockListeners;
	private long lastTick;
	private long lastDraw;
	
	private int gameTickLength = 1000;
	private int redrawTime = 10;
	
	public Clock(){
		gameClockListeners = new LinkedList<GameClockListener>();
		drawingClockListeners = new LinkedList<DrawingClockListener>();
		init(gameTickLength < redrawTime ? gameTickLength : redrawTime);
	}

	public Clock(int millis){
		gameClockListeners = new LinkedList<GameClockListener>();
		drawingClockListeners = new LinkedList<DrawingClockListener>();
		init(millis);
	}
	
	private void init(int millis){
		timer = new Timer(millis, this);
		timer.start();
		lastTick = lastDraw = System.currentTimeMillis();
	}
	
	public void addGameClockListener(GameClockListener gcl){
		gameClockListeners.add(gcl);
	}
	
	public void addDrawingClockListener(DrawingClockListener dcl){
		drawingClockListeners.add(dcl);
	}
	
	public void removeGameClockListener(GameClockListener gcl){
		gameClockListeners.remove(gcl);
	}
	
	public void removeDrawingClockListener(DrawingClockListener dcl){
		drawingClockListeners.remove(dcl);
	}
	
	

	@Override
	public void actionPerformed(ActionEvent arg0) {
		if(System.currentTimeMillis() - lastTick >= gameTickLength){
			lastTick = System.currentTimeMillis();
			for(GameClockListener gcl : gameClockListeners){
				gcl.tick();
			}
		}
		if(System.currentTimeMillis() - lastDraw >= redrawTime){
			lastDraw = System.currentTimeMillis();
			for(DrawingClockListener dcl : drawingClockListeners){
				dcl.draw();
			}
		}
	}
}
